import axios from 'axios'
import { ElMessageBox, ElNotification } from 'element-plus'

const request = axios.create({
  baseURL: import.meta.env.VITE_REQUEST_BASE_URL,
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const loginData = localStorage.getItem('login')
    if (loginData) {
      const { access_token } = JSON.parse(loginData)
      config.headers.Authorization = `Bearer ${access_token}`
    }
    return config
  },
  (error) => {
    ElNotification({
      title: '请求错误',
      message: error.message || '请求发送失败',
      type: 'error',
    })
    console.log('request error', error)

    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.data && response.data.code === 200) {
      return response.data
    } else {
      ElNotification({
        title: 'Error',
        message: response.data?.message,
        type: 'error',
      })
      return Promise.reject(response.data)
    }
  },
  (error) => {
    ElNotification({
      title: '错误',
      message: error.response?.data?.message || error.message || '请求失败',
      type: 'error',
    })

    if (error.response?.data?.code === 401) {
      //如果token失效，先清除本地缓存的token，再刷新页面，结合前端路由拦截器，会重定向到登录界面
      if (localStorage.getItem('login')) {
        localStorage.removeItem('login')
        ElMessageBox.alert('登录已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登陆',
          callback: () => {
            location.reload()
          },
        })
      }
    }
    return Promise.reject(error.response?.data)
  },
)

export default request
